# Replication code for Table 2 in Jenke & Sullivan, "Attention and Political Choice: A Foundation for Eye Tracking in Political Science," Political Analysis.
# Written by Libby Jenke

rm(list = ls())

library(ggplot2)
library(dplyr)
library(htmltools)
library(gt)
devtools::install_github("libbyjenke/EyeMetrics")
library(EyeMetrics)

# Insert working directory below
setwd("....")

# Load data ---------------------------------------------------------------
eye_dat <- read.csv("data/sample_data.csv")

# Get data set ---------------------------------------------------------------
# Rename variables
fixation_data <- eye_dat |>
  rename(
    subject_id = Respondent.Name,
    aoi_num = AOI.Label,
    fix_duration = Fixation.Duration,
    trials = trial_num
  )
#Get only subject 3's data
fixation_data <- fixation_data |>
  filter(subject_id == 3)

# Make sure that trials is numeric
fixation_data$trials <- as.numeric(fixation_data$trials)

# Define trial number(s) that you want to examine
trial_number <- 1

# Get rid of any 0s for AOI numbers
fixation_data <- fixation_data[!is.na(fixation_data$aoi_num),]

# Table 2 ---------------------------------------------------------------
# Use the EyeMetrics function (Jenke and Sullivan, 2025)
output <- EyeMetrics(fixation_data, trial_number)

# Get output in nice table form
output_final <- output |>
  ungroup() |>
  select(c("aoi_num","num_fix","tot_fix_time","num_returns","percentage_aoi_fix_time","first_aoi"))
table_output <- output_final |>
  gt() |>
  tab_header(
    title = "Table 2"
  ) |>
  cols_label(
    aoi_num = "AOI",
    num_fix = "Number of fixations",
    tot_fix_time = "Total Fixation Time (ms)",
    num_returns = "Number of returns",
    percentage_aoi_fix_time = "Total fixation percentage",
    first_aoi = "First fixated option"
  )

# Save table
save_html(table_output,"output/table2.html")
